import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import { Response, Request } from 'express';

export interface ErrorResponse {
  code: number;
  message: string;
  timestamp: string;
  path: string;
}


@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const errorResponse: ErrorResponse = {
      code: status,
      message: exception.message || '服务器错误',
      timestamp: new Date().toISOString(),
      path: request.url,
    };
    response.status(status).json({
      code: errorResponse.code,
      message: errorResponse.message,
      data: null,
      timestamp: errorResponse.timestamp,
      path: errorResponse.path,
    });
  }
}